import React, { useEffect, useState, useRef } from "react";
import { consultationService, handleApiResponse, handleApiError } from "../../../utils/api";
import { useParams, useNavigate } from "react-router-dom";
import TopNav from "../../../components/topNav";
import cup from '../../../assets/hdpi/cup.png'
import certificate from '../../../assets/hdpi/certificate.png'
import flower from '../../../assets/hdpi/flower.png'
import common_icon_attention_small_n from '../../../assets/icon/common_icon_attention_small_n.png'
import common_icon_attention_small_s from '../../../assets/icon/common_icon_attention_small_s.png'
import './index.css';

const Index: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [doctorData, setDoctorData] = useState<any>(null);
  const [evaluations, setEvaluations] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [isFollowed, setIsFollowed] = useState(false);
  const [followLoading, setFollowLoading] = useState(false);
  
  // 从localStorage获取用户信息
  const [userInfo, setUserInfo] = useState<any>(null);
  
  // 从localStorage获取关注状态
  const getLocalFollowState = (doctorId: string) => {
    try {
      const stored = localStorage.getItem(`doctorFollow_${doctorId}`);
      return stored ? JSON.parse(stored) : null;
    } catch (error) {
      console.error('获取本地关注状态失败:', error);
      return null;
    }
  };
  
  // 保存关注状态到本地
  const saveLocalFollowState = (doctorId: string, isFollowed: boolean) => {
    try {
      localStorage.setItem(`doctorFollow_${doctorId}`, JSON.stringify(isFollowed));
    } catch (error) {
      console.error('保存本地关注状态失败:', error);
    }
  };
  
  useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      try {
        setUserInfo(JSON.parse(storedUserInfo));
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }
    }
  }, []);

  // 处理关注/取消关注
  const handleFollowToggle = async () => {
    if (!id || followLoading || !userInfo) return;
    
    setFollowLoading(true);
    try {
      if (isFollowed) {
        // 取消关注
        await consultationService.cancelFollowDoctor({ 
          doctorId: id, 
          userId: userInfo.userId, 
          sessionId: userInfo.sessionId 
        });
        setIsFollowed(false);
        // 保存到本地
        saveLocalFollowState(id, false);
        console.log('取消关注成功');
      } else {
        // 关注医生
        await consultationService.followDoctor({ 
          doctorId: id, 
          userId: userInfo.userId, 
          sessionId: userInfo.sessionId 
        });
        setIsFollowed(true);
        // 保存到本地
        saveLocalFollowState(id, true);
        console.log('关注成功');
      }
    } catch (error) {
      console.error('操作失败:', handleApiError(error));
      // 操作失败时恢复原状态
      setIsFollowed(!isFollowed);
    } finally {
      setFollowLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      const getDoctorDetail = async () => {
        setLoading(true);
        try {
          const response = await consultationService.getDoctorDetail(id);
          const data = handleApiResponse(response) as any;
          setDoctorData(data);
          
          // 优先使用本地存储的关注状态，其次使用接口返回的followFlag
          const localFollowState = getLocalFollowState(id);
          const apiFollowState = data.followFlag === 1; // followFlag: 1-已关注, 2-未关注
          
          // 使用 || 逻辑：优先本地，其次接口
          const finalFollowState = localFollowState !== null ? localFollowState : apiFollowState;
          setIsFollowed(finalFollowState);
          
          // 如果本地没有数据，保存接口数据到本地
          if (localFollowState === null) {
            saveLocalFollowState(id, apiFollowState);
          }
          
          console.log('关注状态:', { 
            doctorId: id, 
            localFollowState, 
            apiFollowState, 
            finalFollowState 
          });
          console.log('医生详情:', data);
        } catch (error) {
          console.error('获取医生详情失败:', handleApiError(error));
        } finally {
          setLoading(false);
        }
      };
      
      const getDoctorEvaluations = async () => {
        try {
          const response = await consultationService.getDoctorEvaluations({
            doctorId: id,
            page: 1,
            count: 3
          });
          const data = handleApiResponse(response) as any[];
          setEvaluations(data || []);
          console.log('医生评价:', data);
        } catch (error) {
          console.error('获取医生评价失败:', handleApiError(error));
          setEvaluations([]);
        }
      };
      
      getDoctorDetail();
      getDoctorEvaluations();
    }
  }, [id]);


  if (loading) {
    return (
      <div className="doctor-detail">
        <TopNav title="医生详情" />
        <div className="loading">加载中...</div>
      </div>
    );
  }

  if (!doctorData) {
    return (
      <div className="doctor-detail">
        <TopNav title="医生详情" />
        <div className="loading">暂无数据</div>
      </div>
    );
  }

  return (
    <div className="doctor-detail">
      <TopNav title="医生详情" />
      

      <div className="doctor-card">
        <div className="doctor-avatar">
          <img src={doctorData.imagePic} alt={doctorData.doctorName} />
        </div>
        
        <div className="doctor-detail-info">
          <div className="attention-btn" onClick={handleFollowToggle}>
            <img 
              src={isFollowed ? common_icon_attention_small_s : common_icon_attention_small_n} 
              alt="关注" 
              style={{ opacity: followLoading ? 0.6 : 1 }}
            />
          </div>
          <div className="doctor-name">{doctorData.doctorName}</div>
          <div className="doctor-title">{doctorData.jobTitle}</div>
          <div className="doctor-hospital">{doctorData.inauguralHospital}</div>
          
          <div className="doctor-stats">
            <span className="rating">好评率 {doctorData.praise}</span>
            <span className="patients">服务患者数 {doctorData.serverNum}</span>
          </div>
          
          <div className="doctor-gift">
            <span>| 他收到的礼物</span>
            <div className="gift-icons">
              <div className="gift-item">
                <img src={flower} alt="花朵" />
                <span>12</span>
              </div>
              <div className="gift-item">
                <img src={certificate} alt="证书" />
                <span>8</span>
              </div>
              <div className="gift-item">
                <img src={cup} alt="奖杯" />
                <span>20</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 个人简介 */}
      <div className="section">
        <div className="section-title">
          <div className="title-icon"></div>
          <span>个人简介</span>
        </div>
        <div className="section-content">
          {doctorData.personalProfile}
        </div>
      </div>

      {/* 擅长领域 */}
      <div className="section">
        <div className="section-title">
          <div className="title-icon"></div>
          <span>擅长领域</span>
        </div>
        <div className="section-content">
          {doctorData.goodField}
        </div>
      </div>

      {/* 用户评价 */}
      <div className="section">
        <div className="section-title">
          <div className="title-icon"></div>
          <span>用户评价</span>
          <span className="comment-count">（{evaluations.length}条评价）</span>
        </div>
        
        <div className="comments-list">
          {evaluations.length > 0 ? (
            evaluations.map((evaluation, index) => (
              <div 
                key={index} 
                className={`comment-item ${index === 1 ? 'comment-partial' : ''}`}
              >
                <div className="comment-header">
                  <img 
                    src={evaluation.headPic || common_icon_attention_small_n} 
                    alt="头像" 
                    className="comment-avatar" 
                  />
                  <div className="comment-user">
                    <div className="username">{evaluation.nickName || '匿名用户'}</div>
                    <div className="comment-time">
                      {evaluation.commentTime ? 
                        new Date(evaluation.commentTime).toLocaleDateString() : 
                        '未知时间'
                      }
                    </div>
                  </div>
                </div>
                <div className="comment-content">
                  {evaluation.content || '暂无评价内容'}
                </div>
              </div>
            ))
          ) : (
            <div className="comment-item">
              <div className="comment-content" style={{ textAlign: 'center', color: '#999' }}>
                暂无评价
              </div>
            </div>
          )}
        </div>
        
        <div className="view-more" onClick={() => navigate(`/moreComment/${id}`)}>
          <span>点击查看更多评论</span>
        </div>
      </div>

      {/* 底部咨询按钮 */}
      <div className="bottom-bar">
        <div className="price">
          <span className="price-amount">{doctorData.servicePrice}币/次</span>
        </div>
        <button className="consult-btn" onClick={() => navigate(`/doctorChat/${id}`)}>
          立即咨询
        </button>
      </div>
    </div>
  );
};

export default Index;
